<script setup>
import { ref, onMounted, reactive } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Search, Coin, RefreshRight, Plus } from '@element-plus/icons-vue';

const key = ref('');
const maxPrice = ref('');
const cartData = ref([]);
const dialogVisible = ref(false);
const editingItem = reactive({
  goods_id: null,
  goods_name: '',
  goods_img: '',
  goods_price: 0,
  goods_count: 1
});
const newItemForm = ref(null);

const rules = reactive({
  goods_name: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' },
    { min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }
  ],
  goods_img: [
    { required: true, message: '商品图片URL不能为空', trigger: 'blur' }
  ],
  goods_price: [
    { required: true, type: 'number', message: '商品价格不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '商品价格不能小于0', trigger: 'blur' }
  ],
  goods_count: [
    { required: true, type: 'number', message: '商品数量不能为空', trigger: 'blur' },
    { type: 'number', min: 1, max: 999, message: '请输入正常数量', trigger: 'blur' }
  ],
});

onMounted(() => {
  axios.get("https://applet-base-api-t.itheima.net/api/cart").then((res) => {
    if (res.status === 200) {
      cartData.value = res.data.list;
    }
  });
});

const resetEditingItem = function ()  {
  Object.assign(editingItem, {
    goods_id: null,
    goods_name: '',
    goods_img: '',
    goods_price: 0,
    goods_count: 1
  });
};

const handleDelete = function (index)  {
  cartData.value.splice(index, 1);
};

const handleEdit = function (index, row)  {
  Object.assign(editingItem, row);
  dialogVisible.value = true;
};

const searchBtn = function ()  {
  if (!key.value && !maxPrice.value) {
    axios.get("https://applet-base-api-t.itheima.net/api/cart").then((res) => {
      if (res.status === 200) {
        cartData.value = res.data.list;
      }
    });
    return;
  }
  cartData.value = cartData.value.filter(item => {
    const matchesKey = key.value ? item.goods_name.includes(key.value) : true;
    const matchesPrice = maxPrice.value ? item.goods_price <= parseFloat(maxPrice.value) : true;
    return matchesKey && matchesPrice;
  });
};

const reSet = function ()  {
  axios.get("https://applet-base-api-t.itheima.net/api/cart").then((res) => {
    if (res.status === 200) {
      cartData.value = res.data.list;
      key.value = '';
      maxPrice.value = '';
    }
  });
};

const add = function ()  {
  resetEditingItem();
  dialogVisible.value = true;
};

const saveEdit = function ()  {
  newItemForm.value.validate((valid) => {
    if (valid) {
      if (editingItem.goods_id) {
        const index = cartData.value.findIndex(item => item.goods_id === editingItem.goods_id);
        if (index !== -1) {
          cartData.value.splice(index, 1, { ...editingItem });
        }
      } else {
        editingItem.goods_id = Date.now();
        cartData.value.push({ ...editingItem });
      }
      dialogVisible.value = false;
    } else {
      ElMessage.error('请填写正确的商品信息');
    }
  });
};
</script>

<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>购物车管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="title">
      <div class="search_box">
        <el-input
            v-model="key"
            class="input_1"
            clearable
            placeholder="搜索关键字"
            :prefix-icon="Search"
        />
        <el-input
            v-model="maxPrice"
            class="input_1"
            clearable
            placeholder="最大单价￥"
            :suffix-icon="Coin"
        />
        <el-button type="primary" :icon="Search" class="btn" @click="searchBtn">搜索</el-button>
        <el-button type="info" :icon="RefreshRight" class="btn" @click="reSet">重置</el-button>
        <el-button type="success" :icon="Plus" class="btn" @click="add">新增</el-button>
      </div>
    </div>

    <el-table :data="cartData" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column label="商品图片" width="120">
        <template #default="scope">
          <img :src="scope.row.goods_img" alt="商品图片" style="width: 100px; height: auto;">
        </template>
      </el-table-column>
      <el-table-column prop="goods_name" label="商品名称" width="180" />
      <el-table-column prop="goods_price" label="商品价格" width="100" />
      <el-table-column label="商品数量" width="180">
        <template #default="scope">
          <el-input-number v-model="scope.row.goods_count" :min="1" size="small" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除这个商品吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button type="text" style="color: #d90f0f" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible">
      <el-form :model="editingItem" :rules="rules" ref="newItemForm">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editingItem.goods_name" />
        </el-form-item>
        <el-form-item label="商品图片" prop="goods_img">
          <img v-if="editingItem.goods_img" :src="editingItem.goods_img" alt="商品图片" class="goods-image">
          <el-input v-model="editingItem.goods_img" v-else />
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input-number v-model="editingItem.goods_price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_count">
          <el-input-number v-model="editingItem.goods_count" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search_box{
  height: 50px;
  display: flex;
  align-items: center;
}
.input_1{
  width: 200px;
  margin-left: 25px;
  margin-right: 25px;
}
.btn{
  height: 38px;
}
.title{
  margin-top: 15px;
  padding-top: 12px;
  background-color: white;
}
.goods-image {
  border: 1px black solid;
  width: 50%;
  height: auto;
  display: block;
  margin-bottom: 20px;
}
</style>
